package com.icehand.echarts.web.util;

import com.alibaba.fastjson.JSONObject;
import com.icehand.echarts.model.EchartsOption;
import org.springframework.util.Base64Utils;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;

/**
 * @author zhoujunmei
 * @date 2019-08-05
 */
public class EchartImageCreator {
    public static ImageResult create(String pahantomjsPath, String imagePath, EchartsOption echartsOption) throws FileNotFoundException {
        if (echartsOption == null) {
            return new ImageResult();
        }
        ImageRenderParams params = new ImageRenderParams()
                .setOpt(echartsOption)
                .setOutfile(imagePath);
        String jsonStr = JSONObject.toJSONString(params);
        //转换为base64编码是为了防止执行指令的时候出问题
        byte[] bytes = Base64Utils.encode(jsonStr.getBytes(StandardCharsets.UTF_8));

        //调用的JS文件路径
        File jsFile = ResourceUtils.getFile("classpath:static/js/echarts-convert.js");
        // 生成的图片名称
        String jsFilePath = jsFile.getAbsolutePath();
        String[] args = new String[2];
        args[0] = jsFilePath;
        args[1] = new String(bytes);
        // 执行脚本
        try {
            CommandExecUtil.phantomjsExec(pahantomjsPath, args);
        } catch (Exception e) {
            throw e;
        }

        return new ImageResult().setPath(imagePath);
    }
}
